using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace Yuekao.API.Write.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FileUploadController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;
        private readonly ILogger<FileUploadController> _logger;

        public FileUploadController(IWebHostEnvironment environment, ILogger<FileUploadController> logger)
        {
            _environment = environment;
            _logger = logger;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <returns>上传结果</returns>
        [HttpPost("upload-image")]
        public async Task<IActionResult> UploadImage(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new { success = false, message = "请选择要上传的图片文件" });
                }

                // 检查文件类型
                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                
                if (!allowedExtensions.Contains(fileExtension))
                {
                    return BadRequest(new { success = false, message = "只支持 JPG、JPEG、PNG、GIF、BMP、WEBP 格式的图片" });
                }

                // 检查文件大小 (限制为 10MB)
                if (file.Length > 10 * 1024 * 1024)
                {
                    return BadRequest(new { success = false, message = "图片文件大小不能超过 10MB" });
                }

                // 创建上传目录
                var uploadPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid()}{fileExtension}";
                var filePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 返回可访问的URL
                var fileUrl = $"{Request.Scheme}://{Request.Host}/uploads/images/{fileName}";

                _logger.LogInformation($"图片上传成功: {fileName}, 大小: {file.Length} bytes");

                return Ok(new
                {
                    success = true,
                    message = "图片上传成功",
                    data = new
                    {
                        fileName = fileName,
                        originalName = file.FileName,
                        fileSize = file.Length,
                        fileUrl = fileUrl,
                        uploadTime = DateTime.Now
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "图片上传失败");
                return StatusCode(500, new { success = false, message = "图片上传失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 批量上传图片
        /// </summary>
        /// <param name="files">图片文件列表</param>
        /// <returns>上传结果</returns>
        [HttpPost("upload-images")]
        public async Task<IActionResult> UploadImages(IFormFileCollection files)
        {
            try
            {
                if (files == null || files.Count == 0)
                {
                    return BadRequest(new { success = false, message = "请选择要上传的图片文件" });
                }

                if (files.Count > 10)
                {
                    return BadRequest(new { success = false, message = "一次最多只能上传 10 张图片" });
                }

                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var uploadResults = new List<object>();

                foreach (var file in files)
                {
                    if (file.Length == 0) continue;

                    var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
                    
                    if (!allowedExtensions.Contains(fileExtension))
                    {
                        continue; // 跳过不支持的文件类型
                    }

                    if (file.Length > 10 * 1024 * 1024)
                    {
                        continue; // 跳过过大的文件
                    }

                    // 创建上传目录
                    var uploadPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
                    if (!Directory.Exists(uploadPath))
                    {
                        Directory.CreateDirectory(uploadPath);
                    }

                    // 生成唯一文件名
                    var fileName = $"{Guid.NewGuid()}{fileExtension}";
                    var filePath = Path.Combine(uploadPath, fileName);

                    // 保存文件
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    // 生成可访问的URL
                    var fileUrl = $"{Request.Scheme}://{Request.Host}/uploads/images/{fileName}";

                    uploadResults.Add(new
                    {
                        fileName = fileName,
                        originalName = file.FileName,
                        fileSize = file.Length,
                        fileUrl = fileUrl,
                        uploadTime = DateTime.Now
                    });
                }

                _logger.LogInformation($"批量图片上传成功: {uploadResults.Count} 张图片");

                return Ok(new
                {
                    success = true,
                    message = $"成功上传 {uploadResults.Count} 张图片",
                    data = uploadResults
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量图片上传失败");
                return StatusCode(500, new { success = false, message = "批量图片上传失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>删除结果</returns>
        [HttpDelete("delete-image/{fileName}")]
        public IActionResult DeleteImage(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    return BadRequest(new { success = false, message = "文件名不能为空" });
                }

                var uploadPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
                var filePath = Path.Combine(uploadPath, fileName);

                if (!System.IO.File.Exists(filePath))
                {
                    return NotFound(new { success = false, message = "文件不存在" });
                }

                System.IO.File.Delete(filePath);

                _logger.LogInformation($"图片删除成功: {fileName}");

                return Ok(new
                {
                    success = true,
                    message = "图片删除成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "图片删除失败");
                return StatusCode(500, new { success = false, message = "图片删除失败，请稍后重试" });
            }
        }

        /// <summary>
        /// 获取图片列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns>图片列表</returns>
        [HttpGet("list")]
        public IActionResult GetImageList([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
        {
            try
            {
                var uploadPath = Path.Combine(_environment.WebRootPath, "uploads", "images");
                
                if (!Directory.Exists(uploadPath))
                {
                    return Ok(new
                    {
                        success = true,
                        data = new List<object>(),
                        total = 0,
                        page = page,
                        pageSize = pageSize
                    });
                }

                var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp" };
                var imageFiles = Directory.GetFiles(uploadPath)
                    .Where(file => allowedExtensions.Contains(Path.GetExtension(file).ToLowerInvariant()))
                    .Select(file => new
                    {
                        fileName = Path.GetFileName(file),
                        fileSize = new FileInfo(file).Length,
                        uploadTime = new FileInfo(file).CreationTime,
                        fileUrl = $"{Request.Scheme}://{Request.Host}/uploads/images/{Path.GetFileName(file)}"
                    })
                    .OrderByDescending(x => x.uploadTime)
                    .ToList();

                var total = imageFiles.Count;
                var pagedFiles = imageFiles.Skip((page - 1) * pageSize).Take(pageSize).ToList();

                return Ok(new
                {
                    success = true,
                    data = pagedFiles,
                    total = total,
                    page = page,
                    pageSize = pageSize
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取图片列表失败");
                return StatusCode(500, new { success = false, message = "获取图片列表失败，请稍后重试" });
            }
        }
    }
} 